package com.pinyoumei.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pinyoumei.base.TaotaoResult;
import com.pinyoumei.utils.JsonUtils;
import com.pinyoumei.web.fegin.CallBackServiceFeign;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/alipay/callback")
public class CallBackController {
	
	@Autowired
	private CallBackServiceFeign callBackServiceFeign;

	/**
	 * @param request
	 * @return
	 * v1.0 同步回调
	@RequestMapping("/return_url")
	public String synCallBack(HttpServletRequest request){
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]:valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		log.info("支付宝同步回调CallBackController.synCallBack开始params:{}",JsonUtils.objectToJson(params));
		String result=callBackServiceFeign.synCallBack(params);
		TaotaoResult taotaoResult=JsonUtils.jsonToPojo(result, TaotaoResult.class);
		if(taotaoResult.getStatus()!=200){
			return "pay/error";//跳转错误页面
		}
		HashMap<String,Object> data=(HashMap<String, Object>) taotaoResult.getData();
		String outTradeNo = (String) data.get("outTradeNo");// 商户订单号
		request.setAttribute("outTradeNo", outTradeNo);
		String tradeNo = (String) data.get("tradeNo");//支付宝交易号
		request.setAttribute("tradeNo", tradeNo);
		String totalAmount =(String) data.get("totalAmount");// 付款金额
		request.setAttribute("totalAmount", totalAmount);
		log.info("支付宝同步回调CallBackController.synCallBack结束data:{}",JsonUtils.objectToJson(data));
		return "pay/success";//跳转成功页面
		
	}
	*/
	
	/**
	 * 同步回调
	 * @param request
	 * @return
	 * v2.0 解决get参数暴露问题,响应一个form表单页面
	 * @throws IOException 
	 
	@RequestMapping("/return_url")
	public void synCallBack(HttpServletRequest request,HttpServletResponse response) throws IOException{
		//告诉浏览器,服务器响应的是一个html页面
		response.setContentType("text/html;charset=utf-8");
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]:valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		log.info("支付宝同步回调CallBackController.synCallBack开始params:{}",JsonUtils.objectToJson(params));
		String result=callBackServiceFeign.synCallBack(params);
		TaotaoResult taotaoResult=JsonUtils.jsonToPojo(result, TaotaoResult.class);
		PrintWriter writer = response.getWriter();
		if(taotaoResult.getStatus()!=200){
			String msg=taotaoResult.getMsg();
			writer.println(msg);
			writer.close();
			return ;//跳转错误页面
		}
		HashMap<String,Object> data=(HashMap<String, Object>) taotaoResult.getData();
		log.info("支付宝同步回调CallBackController.synCallBack结束data:{}",JsonUtils.objectToJson(data));
		String htmlFrom = "<form name='punchout_form'"
				+ " method='post' action='http://localhost:8080/alipay/callback/synSuccessPage' >"
				+ "<input type='hidden' name='outTradeNo' value='" + data.get("outTradeNo") + "'>"
				+ "<input type='hidden' name='tradeNo' value='" +data.get("tradeNo") + "'>"
				+ "<input type='hidden' name='totalAmount' value='" + data.get("totalAmount") + "'>"
				+ "<input type='submit' value='立即支付' style='display:none'>"
				+ "</form><script>document.forms[0].submit();" + "</script>";
		writer.println(htmlFrom);
		writer.close();
		
	}
	*/
	
	/**
	 * 同步回调
	 * @param request
	 * @return
	 * v3.0 解决get参数暴露问题,响应一个视图
	 * @throws IOException 
	 */
	@RequestMapping("/return_url")
	public String synCallBack(@RequestParam Map<String, String> params,Model model){
		/**
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]:valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		*/
		log.info("支付宝同步回调CallBackController.synCallBack开始params:{}",JsonUtils.objectToJson(params));
		String result=callBackServiceFeign.synCallBack(params);
		TaotaoResult taotaoResult=JsonUtils.jsonToPojo(result, TaotaoResult.class);
		if(taotaoResult.getStatus()!=200){
			String msg=taotaoResult.getMsg();
			//request.setAttribute("msg", msg);
			model.addAttribute("msg", msg);
			return "pay/fail";//跳转错误页面
		}
		HashMap<String,Object> data=(HashMap<String, Object>) taotaoResult.getData();
		log.info("支付宝同步回调CallBackController.synCallBack结束data:{}",JsonUtils.objectToJson(data));
		//request.setAttribute("outTradeNo",data.get("outTradeNo"));
		//request.setAttribute("tradeNo", data.get("tradeNo"));
		//request.setAttribute("totalAmount",data.get("totalAmount"));
		model.addAttribute("outTradeNo", data.get("outTradeNo"));
		model.addAttribute("tradeNo", data.get("tradeNo"));
		model.addAttribute("totalAmount", data.get("totalAmount"));
		return "pay/form";//跳转一个临时form表单页面
	}
	
	// 同步回调,解决隐藏参数
	@RequestMapping(value = "/synSuccessPage", method = RequestMethod.POST)
	public String synSuccessPage(@RequestParam("outTradeNo")String outTradeNo, @RequestParam("tradeNo")String tradeNo, @RequestParam("totalAmount")String totalAmount,HttpServletRequest request) {
		request.setAttribute("outTradeNo", outTradeNo);
		request.setAttribute("tradeNo", tradeNo);
		request.setAttribute("totalAmount", totalAmount);
		return "pay/success";
	}
	
	//异步回调
	@ResponseBody
	@RequestMapping("/notify_url")
	public String asynCallBack(@RequestParam Map<String, String> params){
		log.info("支付宝异步回调开始params:{}",JsonUtils.objectToJson(params));
		//返回success或fail
		String result=callBackServiceFeign.asynCallBack(params);
		return result;
		
	}

}
